<template>
  <div class="comment-section">
    <!-- 评论统计 -->
    <div class="comment-header">
      <h3>评论 ({{ comments.length }})</h3>
    </div>

    <!-- 发表评论 -->
    <div class="comment-form">
      <el-form :model="commentForm" ref="commentFormRef" :rules="commentRules">
        <el-form-item prop="content">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmitComment" :loading="submitting">
            发表评论
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list">
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <div class="comment-main">
          <div class="comment-avatar">
            <el-avatar :src="comment.userAvatar" :size="40">
              {{ comment.userName?.charAt(0) }}
            </el-avatar>
          </div>
          <div class="comment-content">
            <div class="comment-header">
              <span class="comment-author">{{ comment.userName }}</span>
              <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-actions">
              <el-button type="text" size="small" @click="handleReply(comment)">
                回复
              </el-button>
              <el-button 
                v-if="comment.userId === currentUserId" 
                type="text" 
                size="small" 
                @click="handleDeleteComment(comment)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 回复列表 -->
        <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
          <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
            <div class="reply-main">
              <div class="reply-avatar">
                <el-avatar :src="reply.userAvatar" :size="30">
                  {{ reply.userName?.charAt(0) }}
                </el-avatar>
              </div>
              <div class="reply-content">
                <div class="reply-header">
                  <span class="reply-author">{{ reply.userName }}</span>
                  <span class="reply-time">{{ formatTime(reply.createdAt) }}</span>
                </div>
                <div class="reply-text">
                  <span class="reply-to">回复 @{{ reply.replyToUserName }}：</span>
                  {{ reply.content }}
                </div>
                <div class="reply-actions">
                  <el-button type="text" size="small" @click="handleReply(comment, reply)">
                    回复
                  </el-button>
                  <el-button 
                    v-if="reply.userId === currentUserId" 
                    type="text" 
                    size="small" 
                    @click="handleDeleteReply(reply)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 回复表单 -->
        <div v-if="comment.showReplyForm" class="reply-form">
          <el-form :model="replyForm" ref="replyFormRef" :rules="replyRules">
            <el-form-item prop="content">
              <el-input
                v-model="replyForm.content"
                type="textarea"
                :rows="2"
                :placeholder="`回复 @${replyForm.replyToUserName}：`"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="handleSubmitReply" :loading="submitting">
                回复
              </el-button>
              <el-button size="small" @click="cancelReply">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="comments.length === 0" class="empty-comments">
      <el-empty description="暂无评论，快来发表第一条评论吧！" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getComments, addComment, replyComment, deleteComment } from '@/api/blog'
import { useUserStore } from '@/stores/userInfo'

const props = defineProps({
  blogId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['comment-updated'])

const userStore = useUserStore()
const currentUserId = userStore.userInfo?.id

// 评论列表
const comments = ref([])

// 评论表单
const commentForm = reactive({
  content: ''
})

const commentRules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, max: 500, message: '评论内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

// 回复表单
const replyForm = reactive({
  content: '',
  parentId: null,
  replyToUserId: null,
  replyToUserName: ''
})

const replyRules = {
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 1, max: 300, message: '回复内容长度在 1 到 300 个字符', trigger: 'blur' }
  ]
}

const commentFormRef = ref(null)
const replyFormRef = ref(null)
const submitting = ref(false)

// 获取评论列表
const loadComments = async () => {
  try {
    const res = await getComments(props.blogId)
    if (res.success) {
      comments.value = res.data || []
    }
  } catch (error) {
    ElMessage.error('获取评论失败')
  }
}

// 提交评论
const handleSubmitComment = async () => {
  if (!currentUserId) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    await commentFormRef.value.validate()
    submitting.value = true
    
    const res = await addComment({
      blogId: props.blogId,
      content: commentForm.content
    })
    
    if (res.success) {
      ElMessage.success('评论发表成功')
      commentForm.content = ''
      await loadComments()
      emit('comment-updated')
    }
  } catch (error) {
    ElMessage.error('评论发表失败')
  } finally {
    submitting.value = false
  }
}

// 处理回复
const handleReply = (comment, reply = null) => {
  if (!currentUserId) {
    ElMessage.warning('请先登录')
    return
  }

  // 显示回复表单
  comment.showReplyForm = true
  
  // 设置回复表单数据
  replyForm.parentId = comment.id
  replyForm.replyToUserId = reply ? reply.userId : comment.userId
  replyForm.replyToUserName = reply ? reply.userName : comment.userName
  replyForm.content = ''
}

// 提交回复
const handleSubmitReply = async () => {
  try {
    await replyFormRef.value.validate()
    submitting.value = true
    
    const res = await replyComment({
      blogId: props.blogId,
      parentId: replyForm.parentId,
      content: replyForm.content,
      replyToUserId: replyForm.replyToUserId
    })
    
    if (res.success) {
      ElMessage.success('回复成功')
      cancelReply()
      await loadComments()
      emit('comment-updated')
    }
  } catch (error) {
    ElMessage.error('回复失败')
  } finally {
    submitting.value = false
  }
}

// 取消回复
const cancelReply = () => {
  comments.value.forEach(comment => {
    comment.showReplyForm = false
  })
  replyForm.content = ''
  replyForm.parentId = null
  replyForm.replyToUserId = null
  replyForm.replyToUserName = ''
}

// 删除评论
const handleDeleteComment = async (comment) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteComment({
      commentId: comment.id
    })
    
    if (res.success) {
      ElMessage.success('删除成功')
      await loadComments()
      emit('comment-updated')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 删除回复
const handleDeleteReply = async (reply) => {
  try {
    await ElMessageBox.confirm('确定要删除这条回复吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteComment({
      commentId: reply.id
    })
    
    if (res.success) {
      ElMessage.success('删除成功')
      await loadComments()
      emit('comment-updated')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString()
}

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.comment-section {
  margin-top: 20px;
}

.comment-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.comment-header h3 {
  margin: 0;
  color: #333;
}

.comment-form {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  background: #fff;
}

.comment-main {
  display: flex;
  gap: 12px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #333;
}

.comment-actions {
  display: flex;
  gap: 10px;
}

.reply-list {
  margin-top: 15px;
  margin-left: 50px;
  padding-left: 15px;
  border-left: 2px solid #f0f0f0;
}

.reply-item {
  margin-bottom: 15px;
}

.reply-main {
  display: flex;
  gap: 10px;
}

.reply-content {
  flex: 1;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.reply-author {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.reply-time {
  font-size: 12px;
  color: #999;
}

.reply-text {
  line-height: 1.5;
  color: #333;
}

.reply-to {
  color: #1890ff;
  font-weight: 500;
}

.reply-actions {
  margin-top: 5px;
  display: flex;
  gap: 10px;
}

.reply-form {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.empty-comments {
  text-align: center;
  padding: 40px 0;
  color: #999;
}
</style> 